package gui;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.border.LineBorder;

import server.AdminServer;

public class AdminsFrame extends JFrame {
	private AdminServer server;

	private JPanel containerPanel;
	private String[] userNames;
	private JLabel[] names;
	private RemoveButton[] removeButtons;

	private final Color bkg = new Color(255,99,71);

	public AdminsFrame(AdminServer s){
		server = s;
		
		setSize(300, 400);
		setTitle("Manage Admins");
		containerPanel = new JPanel(new GridLayout(0, 2));
		containerPanel.setBorder(new LineBorder(bkg, 3));
		add(containerPanel);
		
		containerPanel.add(new JLabel("Getting admins..."));
		try {
			userNames = server.getAdminList();
		} catch (RemoteException e) {
			JOptionPane.showMessageDialog(this,
					e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
			dispose();
		}
		containerPanel.removeAll();
		if(userNames.length > 0){
			names = new JLabel[userNames.length];
			removeButtons = new RemoveButton[userNames.length];
			makePanel();
			containerPanel.setBackground(bkg);
			setVisible(true);
		}
		else{
			JOptionPane.showMessageDialog(this,
					"No admins", "", JOptionPane.INFORMATION_MESSAGE);
			dispose();
		}
	}
	
	private void makePanel(){
		for(int i = 0; i < userNames.length; i++){
			names[i] = new JLabel(userNames[i]);
			containerPanel.add(names[i]);
			removeButtons[i] = new RemoveButton(i);
			containerPanel.add(removeButtons[i]);
		}
	}
	
	private class RemoveButton extends JButton{
		private int index;
		public RemoveButton(int i){
			index = i;
			addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					SwingWorker<Object, Object> remover = new SwingWorker<Object, Object>(){
						protected Object doInBackground() throws Exception {
							server.removeAdmin(userNames[index]);
							return null;
						}
						protected void done(){
							try {
								get();
								containerPanel.remove(names[index]);
								containerPanel.remove(removeButtons[index]);
								AdminsFrame.this.validate();
							} catch (Exception e) {
								JOptionPane.showMessageDialog(AdminsFrame.this,
										e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
							}
						}
					};
					remover.execute();
				};
			});
			setText("Remove");
		}
	}
}
